/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cardarus.operatingsystem.struts.actions;

import com.cardarus.operatingsystem.domain.Customer;
import com.cardarus.operatingsystem.domain.SystemUser;
import com.cardarus.operatingsystem.model.BusinessModel;
import java.security.Principal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * Login to the system.
 *
 * This is the action called from the Struts framework.
 * @author Javier Snaider
 */
public class LoginAction extends org.apache.struts.action.Action {

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        HttpSession session = request.getSession();
        Principal principal = request.getUserPrincipal();
        String username;
        if (principal != null) {
            username = request.getUserPrincipal().getName();
            BusinessModel model = BusinessModel.getInstance();

            SystemUser user = model.getUserByUsername(username);
            if (user != null) {
                session.setAttribute("user", user);
                if (user instanceof Customer){
                    return mapping.findForward("customer");
                }
                return mapping.findForward("success");
            }
        }
        session.invalidate();
        return mapping.findForward("error");
    }
}
